package com.zc.demo.xmlparser;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;

/**
 * dom4j组装与解析xml示例
 * Created by zhangchi9 on 2016/12/13.
 */
public class Dom4jParser implements XmlDocument{
    private String fileName;
    public Dom4jParser(){
        this.fileName = "D:\\dom4j.xml";
    }
    @Override
    public void parseXml(String xml) {
        File inputXml = new File(fileName);
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(inputXml);
            Element employees = document.getRootElement();
            for (Iterator i = employees.elementIterator(); i.hasNext();) {
                Element employee = (Element) i.next();
                for (Iterator j = employee.elementIterator(); j.hasNext();) {
                    Element node = (Element) j.next();
                    System.out.println(node.getName() + ":" + node.getText());
                }
            }
        } catch (DocumentException e) {
            System.out.println(e.getMessage());
        }
        System.out.println("dom4j parserXml");
    }

    @Override
    public String assembleXml() {
        // 创建一个文档对象
        Document document = DocumentHelper.createDocument();
        // 在根节点添加元素
        Element employees = document.addElement("employees");
        // 在employees下添加子节点
        Element employee = employees.addElement("employee");
        // 在employee下添加子节点
        Element name = employee.addElement("name");
        // 给name节点添加内容
        name.setText("ddvip");
        Element sex = employee.addElement("sex");
        sex.setText("m");
        Element age = employee.addElement("age");
        age.setText("29");
        try {
            Writer fileWriter = new FileWriter(fileName);
            XMLWriter xmlWriter = new XMLWriter(fileWriter);
            xmlWriter.write(document);
            xmlWriter.close();
        } catch (IOException e) {

            System.out.println(e.getMessage());
        }
        return null;
    }
}
